package com.ljc.interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ljc.util.JWTUtil;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashMap;

public class JWTInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       // System.out.println("请求"+request.getRequestURL());
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        String token = request.getHeader("accessToken");

        HashMap<String, Object> map = new HashMap<>();
        try {
            DecodedJWT decodedJWT = JWTUtil.getTokenInfo(token);
            return true;

        } catch (SignatureVerificationException e){
            //签名异常
            e.printStackTrace();
            map.put("msg","签名异常");
        }catch (TokenExpiredException e){
            //token到期
            e.printStackTrace();
            map.put("msg","token到期");
        }catch (AlgorithmMismatchException e){
            //解密算法不匹配
            e.printStackTrace();
            map.put("msg","算法不一致");
        }catch (Exception e){
            //token无效
            e.printStackTrace();
            map.put("msg","token无效");
        }
        map.put("status",-1);
        String json = new ObjectMapper().writeValueAsString(map);   
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().print(json);
        return false;
    }
}
